package controller

import (
	"common"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"net/url"
	"os"
)

const (
	uploadFolder = "C:/Users/wwei5/Documents/uploads/"
)

// UploadFile 上传文件
func UploadFile(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(500, common.ErrResult("文件上传错误: "+err.Error()))
	}

	// 上传的文件目录
	distFile := uploadFolder + file.Filename

	err = c.SaveUploadedFile(file, distFile)
	if err != nil {
		c.JSON(500, common.ErrResult("文件上传错误: "+err.Error()))
	}

	c.JSON(200, common.SuccessResult("文件地址："+distFile))
}

// DownloadFile 下载文件
func DownloadFile(c *gin.Context) {
	fileName := c.Query("fileName")
	// 读取文件
	distFile := uploadFolder + fileName
	file, err := os.ReadFile(distFile)
	if err != nil {
		c.JSON(common.ServerErr, common.ErrResult("读取文件错误->"+err.Error()))
	}
	// url.PathEscape 解决中文乱码问题
	c.Header("Content-Disposition", "attachment; filename="+url.PathEscape(fileName))
	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Transfer-Encoding", "binary")
	// 输出流文件
	_, err = c.Writer.Write(file)
	if err != nil {
		c.JSON(common.ServerErr, common.ErrResult("写文件错误->"+err.Error()))
	} else {
		c.Writer.WriteHeader(http.StatusOK)
	}
}

// UploadMultiFiles 批量上传文件
func UploadMultiFiles(c *gin.Context) {
	form, err := c.MultipartForm()
	if err != nil {
		c.JSON(common.ServerErr, common.ErrResult(err.Error()))
	}
	files := form.File["files"]
	for _, file := range files {
		// 上传的文件目录
		distFile := uploadFolder + file.Filename
		log.Printf("当前上传的文件是: %s, 地址是：%s \n", file.Filename, distFile)

		err = c.SaveUploadedFile(file, distFile)
		if err != nil {
			c.JSON(500, common.ErrResult("文件上传错误: "+err.Error()))
			return
		}
	}
	c.JSON(common.SuccessCode, common.SuccessResult(fmt.Sprintf("上传成功，共有%d个文件", len(files))))
}
